package com.immediatus.ui.view;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import com.immediatus.engine.Engine;
import com.immediatus.graphics.util.OpenGLWrapper;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class RenderView extends GLSurfaceView{
    private Renderer _renderer;

    public RenderView(final Context context_){
        super(context_);
    }

    public RenderView(final Context context_, final AttributeSet attrs_){
        super(context_, attrs_);
    }

    public void setRenderer(final Engine engine_){
        this.setOnTouchListener(engine_);
        this._renderer = new Renderer(engine_);
        this.setRenderer(this._renderer);
    }

    @Override
    protected void onMeasure(final int w_, final int h_){
        this._renderer._engine.getEngineOptions().getResolutionPolicy().onMeasure(this, w_, h_);
    }

    public void setMeasuredDimensionProxy(final int w_, final int h_){
        this.setMeasuredDimension(w_, h_);
    }


    public static class Renderer implements GLSurfaceView.Renderer{
        private final Engine _engine;

        public Renderer(final Engine engine_){
            this._engine = engine_;
        }

        @Override
        public void onSurfaceChanged(final GL10 gl_, final int w_, final int h_){
            this._engine.setCanvasSize(w_, h_);
            gl_.glViewport(0, 0, w_, h_);
            gl_.glLoadIdentity();
        }

        @Override
        public void onSurfaceCreated(final GL10 gl_, final EGLConfig config_){
            OpenGLWrapper.reset(gl_);

            OpenGLWrapper.setPerspectiveCorrectionHintFastest(gl_);
            OpenGLWrapper.setShadeModelFlat(gl_);

            OpenGLWrapper.disableLightning(gl_);
            OpenGLWrapper.disableDither(gl_);
            OpenGLWrapper.disableDepthTest(gl_);
            OpenGLWrapper.disableMultisample(gl_);

            OpenGLWrapper.enableBlend(gl_);
            OpenGLWrapper.enableTextures(gl_);
            OpenGLWrapper.enableTexCoordArray(gl_);
            OpenGLWrapper.enableVertexArray(gl_);

            OpenGLWrapper.enableCulling(gl_);
            gl_.glFrontFace(GL10.GL_CCW);
            gl_.glCullFace(GL10.GL_BACK);

            OpenGLWrapper.enableExtensions(gl_, this._engine.getEngineOptions().getRenderOptions());
        }

        @Override
        public void onDrawFrame(final GL10 gl_){
            try{
                this._engine.onDrawFrame(gl_);
            } catch (final InterruptedException e){
            }
        }
    }
}
